<template>
    <vol-box :lazy="false" v-model="model" :title="'【' + this.queryDto.deviceNo + '】测量信息查询'" :width="width" :padding="0">
        <div :style="{ height: height + 'px' }">
            <div style="height: 50px;">
                <div style="margin-left:100px;margin-top:20px;ine-height: 1.5;">
                    <el-text class="mx-1" size="default"
                        style="font-size:16px; margin-right:8px;margin-top:5px;">生成时间</el-text>
                    <el-date-picker v-model="queryDto.startTime" type="datetime" placeholder="开始时间"
                        format="YYYY/MM/DD HH:mm:ss" value-format="YYYY/MM/DD HH:mm:ss" />
                    <el-text class="mx-1" size="default"
                        style="margin-left:8px;margin-right:8px;font-size:16px;">至</el-text>
                    <el-date-picker v-model="queryDto.endtime" type="datetime" placeholder="结束时间"
                        format="YYYY/MM/DD HH:mm:ss" value-format="YYYY/MM/DD HH:mm:ss" />
                    <el-button type="primary" icon="Search" style="margin-left:20px; width:100px;"
                        @click="query()">查询</el-button>
                    <div style="float:right;margin-top:8px;margin-right:100px;">
                        <el-text class="mx-1" size="default" style="font-size:18px;">设备状态：</el-text>

                        <el-text v-if="entity.alarmFlag == 0" class="mx-1" size="default"
                            style="font-size:20px;color: green;">正常</el-text>
                        <el-text v-else-if="entity.alarmFlag == 1" class="mx-1" size="default"
                            style="font-size:20px;color: red;">故障</el-text>
                        <el-text v-else class="mx-1" size="default" style="font-size:20px;color:blueviolet;">未知</el-text>
                    </div>
                </div>
                <div :style="{ height: (height - 130) + 'px', width: (width - 20) + 'px', marginTop: '40px' }"
                    id="lineChart">

                </div>
            </div>
        </div>
        <!-- <template #footer>
        <div style="text-align: center;">
          <el-button type="default" size="mini" @click="model = false">关闭</el-button>
        </div>
      </template> -->
    </vol-box>

    <vol-box :lazy="false" v-model="upModel" :title="'【' + this.updateDto.deviceNo + '】设备升级'" :width="600" :padding="0">
        <div  class="upload-container" style="height: 320px;padding-bottom: 20px;">
            <div class="button-group" style="margin-top: 10px;">
                <!-- <el-radio-group style="float: left" v-model="upType">
                    <el-radio size="default" :value="0" style="margin-left: 10px;margin-right: 5px;">升级雷达</el-radio>
                    <el-radio size="default" :value="1">升级主板</el-radio>
                </el-radio-group> -->
                <el-upload style="float: left; " show-file-list ref="uploadFile" accept=".bin" :max-size="maxSize"
                            :on-change="clearMsg" :before-upload="beforeUpload" :data="extraFormData" :action="url">
                    <el-button size="small"><i class="el-icon-folder-opened"></i>选择文件</el-button>
                </el-upload>
                <el-button style="margin-left: 20px; width: 90px;" type="primary" size="small" @click="upload(1)"
                            :loading="loadingStatus">
                        <i class="el-icon-receiving"></i>主板升级</el-button>
                <el-button style="margin-left: 10px; width: 90px;" type="success" size="small" @click="upload(0)"
                            :loading="loadingStatus">
                        <i class="el-icon-help"></i>雷达升级</el-button>
                <el-button type="warning" @click="cancelUpgrade" >
                    <i class="el-icon-close"></i>取消升级</el-button>
               
                <span v-if="isOpen" style="font-size: 12px;color: green; margin-left: 15px;">Socket状态：{{ socketStatus }}</span>
                <span v-else style="font-size: 12px;color: red; margin-left: 15px;">Socket状态：{{ socketStatus }}</span>
            </div>
            <div style="height: 70px;">
                <br>
                <el-progress style="width: 420px;" :percentage="percentage" v-show="progressShow" />
                <div class="text" :class="resultClass" style="margin-top: 15px; margin-left: 5px;color: red;" v-html="msg">
                </div>

            </div>

            <div class="alert">
                <el-alert title="上传说明" type="warning" :closable="false" show-icon>只能上传bin文件,文件大小不超过{{ maxSize
                }}M</el-alert>
            </div>
            <div v-if="file">
                <h3 style="font-size: 14px;">所选文件</h3>
                <div class="file-info" style="font-size: 14px;">
                    <span>文件名：{{ file.name }}</span>
                    <span>大小：{{ (file.size / 1024).toFixed(2) }} KB</span>
                </div>
            </div>
            <div v-show="message" class="v-r-message">
                <h3 class="title">上传结果</h3>
                <div class="text" :class="resultClass" v-html="message"></div>
            </div>

        </div>
    </vol-box>

    <vol-box :lazy="false" v-model="shareModel" :title="'【' + this.shareDto.deviceNo + '】设备分享'" :width="800" :padding="0">
        <div  class="upload-container" style="height: 220px;padding-bottom: 20px;">
            <el-checkbox-group v-model="checkedUsers" style="margin: 10px 20px;">
                <el-checkbox v-for="user in userList" :label="user.user_Id" :key="user.user_Id">{{user.userTrueName}}</el-checkbox>
            </el-checkbox-group>
        </div>
        <div style="display: flex; justify-content: center; align-items: center;height: 10vh;  "> 
            <el-button  type="success" size="small" @click="shareDev()"><el-icon><Share /></el-icon>分享</el-button>
            <el-button  type="info" size="small" @click="shareModel=false"><el-icon><Close /></el-icon>关闭</el-button>
        </div>
    </vol-box>
</template>
<script>
import * as echarts from 'echarts';
import options from "./chartOptions.js";
import VolBox from '@/components/basic/VolBox.vue';
import axios from 'axios'
var $chart1;
export default {
    name: 'App',
    components: {
        VolBox
    },
    data() {
        return {
            model: false,
            upModel: false,
            height: 600,
            width: 2000,
            row: null,
            queryDto: {
                startTime: '',
                endtime: '',
                deviceNo: '',
            },
            maxSize: 30,


            socket: null,
            socketStatus: '关闭',
            isOpen: false,
            urls: axios.defaults.filePathURL,
            //url: 'http://47.107.117.94:9991/api/deviceinfo/uploadFile',//写的是服务器的地址，本地调试需要改
            url: axios.defaults.filePathURL,//写的是服务器的地址，本地调试需要改
            file: null,
            msg: '请选择升级文件！',
            upType: 0,
            percentage: 0.00,
            progressShow: false,
            webSokectDto: {
                type: 0,
                msg: '',
                deviceNo: '',
                progressValue: 0,
            },
            loadingStatus: false,
            updateDto: {
                devId: '',
                deviceNo: ''
            },
            entity:
            {
                timesList: [],
                distance1: [],
                distance2: [],
                distance3: [],
                snr1: [],
                snr2: [],
                snr3: [],
                alarmFlag: 0
            },
            options: options,

            shareModel: false,
            shareDto: {
                deviceId: '',
                deviceNo: '',
                CreateID: 0,
                userIdList:[]
            },
            userList:[],
            checkedUsers: [],
            cities:  ['上海', '北京', '广州', '深圳'],
        };
    },
    mounted() {
        // ... 其他 ECharts 配置和初始化代码
    },
    created() {
        this.height = document.body.clientHeight - 195;
        let width = document.body.clientWidth * 0.88;
        this.width = width < 1000 ? 1000 : width;

        // this.connectWebSocket();
        // setInterval(() => {
        //     if (this.socket && !this.isOpen) {
        //         this.connectWebSocket();
        //     }
        // }, 2000);
    },
    beforeDestroy() {
        if (this.socket) {
            this.socket.close();
        }
    },
    methods: {
        connectWebSocket() {
            // this.socket = new WebSocket(`ws://127.0.0.1:9090`);
            this.socket = new WebSocket(axios.defaults.wsURL);
            this.socket.onopen = () => {
                this.socketStatus = '打开';
                this.isOpen = true;
            };

            this.socket.onmessage = (event) => {
                // 处理接收到的数据
                this.webSokectDto = JSON.parse(event.data);
                console.log('收到数据:', this.webSokectDto.deviceNo);
                if (this.upModel && this.updateDto.deviceNo == this.webSokectDto.deviceNo) {
                    switch (this.webSokectDto.type) {
                        case 0: //准备升级
                            this.progressShow = false;
                            this.percentage = 0;
                            this.msg = this.webSokectDto.msg;
                            break;
                        case 1: //升级中
                            this.progressShow = true;
                            this.percentage = this.webSokectDto.progressValue;
                            this.msg = this.webSokectDto.msg;
                            break;
                        case 2: //升级完成
                            this.progressShow = true;
                            this.percentage = this.webSokectDto.progressValue;
                            this.msg = this.webSokectDto.msg;
                            break;
                        case 3: //升级失败
                            // this.progressShow = false;
                            // this.percentage = 0;
                            this.msg = this.webSokectDto.msg;
                            break;
                    }
                }
            };

            this.socket.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };

            this.socket.onclose = () => {
                this.socketStatus = '关闭';
                this.isOpen = false;
            };
        },
        updateDevice(row) {
            this.upModel = true;
            this.$nextTick(() => {
                // 在这里初始化 ECharts
                // $chart1 = echarts.init(document.getElementById('lineChart'));
                // this.options.line.legend.data = ['你好啊', 'et'];
                // $chart1.setOption(this.options.line);
                // if (!("WebSocket" in window)) {
                //     return this.$Message.error('当前浏览器不支持WebSocket,将无法看到升级过程！');
                // }
                // if (!this.isOpen) {
                //     this.connectWebSocket();
                // };
                this.msg = "请选择升级文件！";
                this.message = '';
                this.file = null;
                this.percentage = 0.00;
                this.progressShow = false;
                this.updateDto.id = row.id;
                this.updateDto.deviceNo = row.deviceNo;
            });
        },
        getFileType() {
            let fileName =
                this.file.name
                    .split('.')
                    .pop()
                    .toLocaleLowerCase() || '';
            if (['bin'].indexOf(fileName) == -1) {
                this.$Message.error('只能选择bin文件');
                return false;
            }
            return true;
        },
        beforeUpload(file) {
            this.file = file;
            if (!this.getFileType()) {
                this.msg = "请选择升级文件"
                return false;
            }
            this.msg = "请点击升级"
            return false;
        },
        upload(type) {
            this.upType = type;
            let _url = this.url;
            if (!_url) {
                return this.$Message.error('没有配置好Url');
            }

            if (!this.file) {
                return this.$Message.error('请选择文件');
            }
            var formData = new FormData();
            formData.append('file', this.file);
            formData.append('upType', this.upType);
            formData.append('id', this.updateDto.id);
            formData.append('deviceNo', this.updateDto.deviceNo);
            this.loadingStatus = true;
            this.msg = "正在上传升级文件...";
            this.http.post(_url, formData, true, { headers: { 'Content-Type': 'multipart/form-data' } }).then(
                (x) => {
                    // this.$refs.uploadFile.clearFiles();
                    this.loadingStatus = false;
                    // this.file = null;
                    if (x.status) {
                        this.percentage = 0;
                        this.msg = "文件上传成功，等待升级...";
                        this.$emit('importExcelAfter', x);
                    } else {
                        this.msg = x.message;
                    }

                    this.message = x.message;
                    this.resultClass = x.status ? 'v-r-success' : 'v-r-error';
                },
                (error) => {
                    this.loadingStatus = false;
                }
            );
        },
        //时间格式化函数，此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
        dateFormat(time) {
            var date = new Date(time);
            var year = date.getFullYear();
            /* 在日期格式中，月份是从0开始的，因此要加0
             * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
             * */
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            // 拼接
            return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        },
        getStartOfDay() {
            const now = new Date();
            now.setHours(0, 0, 0, 0); // 设置小时、分钟、秒和毫秒为0
            return now;
        },
        cancelUpgrade(){
            this.$Message.info('发送取消升级申请');
            let url = 'api/deviceinfo/cancelUpgrade?deviceNo=' + this.updateDto.deviceNo;
            this.http.get(url, {}, false).then(async (x) => {
                debugger;
                if (!x.status) return this.$Message.error(x.message);
                this.$Message.success(x.data);
                this.message='已取消升级申请'
            });
            return;
        },


        open(row) {
            this.row = row;
            debugger;
            this.model = true;

            debugger
            this.entity = {},
                this.$nextTick(() => {
                    // 在这里初始化 ECharts
                    // $chart1 = echarts.init(document.getElementById('lineChart'));
                    // this.options.line.legend.data = ['你好啊', 'et'];
                    // $chart1.setOption(this.options.line);
                    this.queryDto.deviceNo = row.deviceNo
                    this.queryDto.startTime = this.dateFormat(this.getStartOfDay());
                    this.queryDto.endtime = this.dateFormat(new Date());
                    this.query();
                });
        },
        query() {
            let url = 'api/measureinfo/queryMeasureCharts';
            debugger;
            let paramss = this.queryDto;
            debugger;
            this.http.post(url, this.queryDto, true).then((result) => {
                if (!result.status) {
                    return this.$message.error(result.message);
                }
                this.entity = result.data;
                this.showEcharts();
            });
        },
        showEcharts() {
            $chart1 = echarts.init(document.getElementById('lineChart'));
            let option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['目标1距离', '目标1 SNR', '目标2距离', '目标2 SNR', '目标3距离', '目标3 SNR']
                },
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        handleSize: 8
                    },
                    {
                        type: 'inside',
                        show: true,
                        handleSize: 8
                    },
                    {
                        type: 'slider',
                        show: true,
                        yAxisIndex: 0,
                        filterMode: 'empty',
                        width: 12,
                        height: '70%',
                        handleSize: 8,
                        showDataShadow: false,
                        left: '93%'
                    }
                ],
                xAxis: {
                    type: 'category',
                    data: this.entity.timesList, // 假设API返回的数据中包含categories数组
                    axisLabel: {
                        show: false // 设置为false以隐藏X轴数据
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series:  // 假设API返回的数据中包含series数组，每个对象代表一条线
                    [
                        {
                            name: '目标1距离',
                            type: 'line',
                            smooth: true,
                            data: this.entity.distance1,
                        },
                        {
                            name: '目标1 SNR',
                            type: 'line',
                            smooth: true,
                            data: this.entity.snr1,
                        },
                        {
                            name: '目标2距离',
                            type: 'line',
                            smooth: true,
                            data: this.entity.distance2,
                        },
                        {
                            name: '目标2 SNR',
                            type: 'line',
                            smooth: true,
                            data: this.entity.snr2,
                        },
                        {
                            name: '目标3距离',
                            type: 'line',
                            smooth: true,
                            data: this.entity.distance3,
                        },
                        {
                            name: '目标3 SNR',
                            type: 'line',
                            smooth: true,
                            data: this.entity.snr3,
                        }
                    ]
            };
            $chart1.setOption(option);
        },

        shareOpen(row) {
            this.shareModel = true;
            this.$nextTick(() => {
                this.shareDto.deviceId = row.id;
                this.shareDto.deviceNo = row.deviceNo;
                this.shareDto.CreateID = row.CreateID;

                let url = 'api/Sys_User/getEnableAllUser';
                this.http.post(url, null, true).then((result) => {
                    if (!result.status) {
                        return this.$message.error(result.message);
                    }
                    this.userList = result.data;
                });

                let url2 = 'api/deviceShare/getDeviceUserIdsByDevId?deviceId='+row.id;
                this.http.post(url2, null, true).then((result) => {
                    if (!result.status) {
                        return this.$message.error(result.message);
                    }
                    this.checkedUsers = result.data;
                });
            });
        },
        shareDev(){
            this.shareDto.userIdList = this.checkedUsers;
            let url = 'api/deviceShare/updateDeviceSharpUserIds';
            this.http.post(url, this.shareDto, true).then((result) => {
                if (!result.status) {
                        return this.$message.error(result.message);
                }
                return this.$message.success('更新成功');
            });
        }
    },
}
</script>
<style lang="less" scoped>
.upload-container {
    min-height: 250px !important;
    display: inline-block;
    width: 100%;
    padding: 10px;
    border: 1px dashed #989898;
    min-height: 250px;
    border-radius: 5px;

    .alert {
        margin-top: 10px;
    }

    .el-button-group>* {
        display: flex;
    }

    h3 {
        margin: 9px 0px;
    }

    .file-info>span {
        margin-right: 20px;
    }

    .v-r-message {
        margin-top: 10px;

        .title {
            margin-bottom: 2px;
        }

        >.text {
            font-size: 13px;
        }

        .v-r-success {
            color: #02b702;
        }

        .v-r-error {
            color: #dc0909;
        }
    }
}
</style>